const db = require('../db/config');
const { sqlInserPlanItem,
        sqlDeletePlanItem,
        sqlGetPlanItemAll,
        sqlGetPlanItem,
        sqlUpdatePlanItem,
        sqlToggleCompletedStatus
      } = require('../db/planSql');

// 添加计划事项
module.exports.insertPlanItemHandler = function (req, res) {
    // 接收前端传过来的值
    const id = req.body.id,
        content = req.body.content,
        completed = req.body.completed;
    
    db.query(sqlInserPlanItem, [id, content, completed], (error, result) => {
        if (result) {
            res.send({
                msg: '添加成功'
            })
        } else {
            res.send({
                msg: '添加失败'
            })
        }
     });
}

// 删除计划事项
module.exports.deletePlanItemHandler = function (req, res) {
    const id = req.body.id;

    db.query(sqlDeletePlanItem, [id], (error, result) => {
        if (result) {
            res.send({
                msg: '删除成功'
            })
        } else {
            res.send({
                msg: '删除失败'
            })
        }
     });
}
    
// 查找全部计划事项
module.exports.getPlanItemHandler = function (req, res) {

    db.query(sqlGetPlanItemAll, (error, result) => {
        if (result) {
            res.send(result)
        } else {
            res.send({
                msg: '查找失败'
            })
        }
     });
}
    
// 更新计划事项
module.exports.updatePlanItemHandler = function (req, res) {
    const id = req.body.id,
        content = req.body.content,
        completed = req.body.completed,
        oldId = req.body.oldId;
    
    db.query(sqlUpdatePlanItem, [content, completed, id,oldId], (error, result) => {
        if (result) {
            res.send({
                msg: '更新成功'
            })
        } else {
            res.send({
                msg: '更新失败'
            })
        }
     });
}
    
// 切换计划事项完成状态
module.exports.toggleCompletedStatusHandler = function (req, res) {
    const id = req.body.id;
    
    db.query(sqlGetPlanItem, [id], (error, result) => {
        if (result) {
            if (result[0].completed === '0') {
                db.query(sqlToggleCompletedStatus, ['1', id], (e, r) => {
                    if (r) {
                        console.log(r)
                        res.send({
                            msg: '修改为完成状态'
                        })
                    }
                });
            } else {
                db.query(sqlToggleCompletedStatus, ['0', id], (e, r) => {
                    res.send({
                        msg: '修改为未完成状态'
                    })
                });
            }
        } else {
            res.send({
                msg: '查询指定事项失败'
            })
        }
     });
}
